<template>
    <div>
        <el-card>
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-select v-model="status" placeholder="审核状态" style="margin-left: 10px;" clearable
                        @clear="getApplication()">
                        <el-option label="已保存" value="1"></el-option>
                        <el-option label="审核中" value="2"></el-option>
                        <el-option label="不同意" value="10"></el-option>
                        <el-option label="同意" value="5"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="13">
                    <el-button @click="selectByStatus()">查询</el-button>
                </el-col>
                <el-col :span="1" :offset="4">
                    <el-button @click="leaveVisible = true">申请请假</el-button>
                </el-col>
            </el-row>
            <!-- 数据列表 -->
            <el-table :data="tableData.slice((pagenum - 1) * pagesize, pagenum * pagesize)"
                style="width: 100%; margin-top: 20px;">
                <el-table-column type="expand">
                    <template slot-scope="props">
                        <el-form label-position="right" class="demo-table-expand" label-width="100px">
                            <el-form-item label="标题">
                                <span>{{ props.row.title }}</span>
                            </el-form-item>
                            <el-form-item label="申请人">
                                <span>{{ props.row.applyPerson }}</span>
                            </el-form-item>
                            <el-form-item label="申请时间">
                                <span>{{ props.row.applyTime }}</span>
                            </el-form-item>
                            <el-form-item label="申请内容" style="word-wrap: break-word; width: 70%;">
                                <span>{{ props.row.content }}</span>
                            </el-form-item>
                            <el-form-item label="审批人">
                                <span>{{ props.row.approvalPerson }}</span>
                            </el-form-item>
                            <el-form-item label="审批时间">
                                <span>{{ props.row.approvalTime }}</span>
                            </el-form-item>
                            <el-form-item label="审批备注" style="word-wrap: break-word; width: 70%;">
                                <span>{{ props.row.remarks }}</span>
                            </el-form-item>
                            <el-form-item label="离校时间">
                                <span>{{ props.row.leaveTime }}</span>
                            </el-form-item>
                            <el-form-item label="回校时间">
                                <span>{{ props.row.backTime }}</span>
                            </el-form-item>

                            <el-form-item label="审核状态">
                                <template slot-scope="scope">
                                    <div v-if="props.row.status == '已保存'">
                                        <el-tag type="warning">已保存</el-tag>
                                    </div>
                                    <div v-if="props.row.status == '审核中'">
                                        <el-tag>审核中</el-tag>
                                    </div>
                                    <div v-if="props.row.status == '审核通过'">
                                        <el-tag type="success">审核通过</el-tag>
                                    </div>
                                    <div v-if="props.row.status == '审核驳回'">
                                        <el-tag type="danger">审核驳回</el-tag>
                                    </div>
                                </template>
                            </el-form-item>
                            <el-form-item style="text-align: right">
                                <div v-if="props.row.status == '已保存' || props.row.status == '审核驳回'"
                                    style="margin-right: -110%;">
                                    <el-button @click="edit(props.row)">编辑</el-button>
                                </div>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column label="标题" prop="title">
                </el-table-column>
                <el-table-column label="申请人" prop="applyPerson">
                </el-table-column>
                <el-table-column label="审批人" prop="approvalPerson">
                </el-table-column>
                <el-table-column label="审核状态" prop="status">
                    <template slot-scope="scope">
                        <div v-if="scope.row.status == '已保存'">
                            <el-tag type="warning">已保存</el-tag>
                        </div>
                        <div v-if="scope.row.status == '审核中'">
                            <el-tag>审核中</el-tag>
                        </div>
                        <div v-if="scope.row.status == '审核通过'">
                            <el-tag type="success">审核通过</el-tag>
                        </div>
                        <div v-if="scope.row.status == '审核驳回'">
                            <el-tag type="danger">审核驳回</el-tag>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 请假申请 -->
            <el-dialog title="审批申请" :visible.sync="leaveVisible" width="50%" @close="resetForm()">
                <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="申请理由" prop="content">
                        <el-input type="textarea" v-model="ruleForm.content" :autosize="{ minRows: 4 }"></el-input>
                    </el-form-item>
                    <el-form-item label="离校时间" prop="leaveTime">
                        <el-date-picker v-model="ruleForm.leaveTime" value-format="yyyy-MM-dd hh:mm:ss" type="date"
                            placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="返校时间" prop="backTime">
                        <el-date-picker v-model="ruleForm.backTime" value-format="yyyy-MM-dd hh:mm:ss" type="date"
                            placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="审批教师" prop="approvalPersonId">
                        <el-select v-model="ruleForm.approvalPersonId" placeholder="请选择教师" class="input-style" size="large"
                            value-key="value" @change="handleChangeTeacher">
                            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.nickName"
                                :value="item.id" /></el-select>
                    </el-form-item>
                    <el-form-item label="文件上传" prop="annex">
                        <el-upload class="upload-demo" ref="uploadBox" action="action" :before-upload="beforeUpload"
                            :http-request="upload" :auto-upload="false">
                            <el-button size="small" type="primary" @click="fileUpload = true">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                    <el-form-item style="text-align: right">
                        <el-button type="danger" @click="resetForm()">取 消</el-button>
                        <el-button @click="staging()">暂 存</el-button>
                        <el-button type="primary" @click="submitForm()">申 请</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <div class="demo-image__preview">
                <el-image-viewer v-if="imgViewerVisible" :on-close="closeImgViewer" :url-list="urlList"
                    style="z-index:9999" />
            </div>
            <!-- 编辑暂存 -->
            <el-dialog title="审批申请" :visible.sync="StagingVisible" width="50%">
                <el-form :model="StagingForm" :rules="rules" ref="StagingFormRef" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="申请理由" prop="content">
                        <el-input type="textarea" v-model="StagingForm.content" :autosize="{ minRows: 4 }"></el-input>
                    </el-form-item>
                    <el-form-item label="离校时间" prop="leaveTime">
                        <el-date-picker value-format="yyyy-MM-dd hh:mm:ss" v-model="StagingForm.leaveTime" type="date"
                            placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="返校时间" prop="backTime">
                        <el-date-picker v-model="StagingForm.backTime" value-format="yyyy-MM-dd hh:mm:ss" type="date"
                            placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="审批教师" prop="approvalPersonId">
                        <el-select v-model="StagingForm.approvalPersonId" placeholder="请选择教师" class="input-style"
                            size="large" value-key="value" @change="handleChangeTeacherStaging">
                            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.nickName"
                                :value="item.id" /></el-select>
                    </el-form-item>
                    <div v-if="StagingForm.status == '审核驳回'">
                        <el-form-item label="审批备注" prop="remarks">
                            <el-input type="textarea" :row="4" v-model="StagingForm.remarks" disabled></el-input>
                        </el-form-item>
                    </div>
                    <el-form-item label="文件上传" prop="annex">
                        <el-upload class="upload-demo" ref="updateBox" action="action" :before-upload="beforeUpdateUpload"
                            :http-request="updateUpload" :auto-upload="false">
                            <el-button size="small" type="primary" @click="fileUpload1 = true">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                    <el-form-item style="text-align: right">
                        <el-button type="danger" @click="deleteStaging()">删 除</el-button>
                        <el-button @click="updateStaging(StagingForm)">暂 存</el-button>
                        <el-button type="primary" @click="updateSubmit(StagingForm)">申 请</el-button>
                    </el-form-item>
                </el-form>
                <template>
                    <el-table :data="tableData1" style="width: 100%" max-height="250" :key="key">
                        <el-table-column fixed prop="fileName" label="文件名" width="150">
                        </el-table-column>
                        <el-table-column prop="fileLocation" label="文件位置" width="120">
                        </el-table-column>
                        <el-table-column prop="fileType" label="文件类型" width="120">
                        </el-table-column>
                        <el-table-column prop="uploadTime" label="上传时间" width="120">
                        </el-table-column>
                        <el-table-column prop="uploadPerson" label="上传人" width="300">
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" width="120">
                            <template slot-scope="scope">
                                <el-button @click.native.prevent="viewRow(scope.row)" type="text" size="small">
                                    预览
                                </el-button>
                                <el-button @click.native.prevent="deleteRow(scope.row)" type="text" size="small">
                                    移除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </el-dialog>

            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagenum"
                :page-sizes="[1, 2, 5, 10]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper"
                :total="total" style="margin-top: 10px; text-align: center">
            </el-pagination>
        </el-card>
    </div>
</template>
<script>
const formData = new FormData()
const formData1 = new FormData()


import { GetBinDingAPI } from '@/components/utils/api/sysfile_api.js'
import {
    GetApplicationInfoListAPI,
    AddApplicationInfoAPI,
    UpdateApplicationInfoAPI,
    RemoveApplicationInfoAPI
} from '@/components/utils/api/application_api.js'
import {
    GetUserInfoListByParamsAPI
} from '@/components/utils/api/user_api.js'
import { postImage, RemoveInfo } from '@/components/utils/api/sysfile_api.js'

export default {
    components: {
        'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer')
    },
    data() {
        return {
            fileUpload1: false,
            fileUpload: false,
            key: 1,
            imgViewerVisible: false,
            url: "",
            urlList: [],
            UpdateStaging: false,
            UpdateAdding: false,
            adding: false,
            staginging: false,
            annexId: '',
            annex: [],
            tableData1: [],
            status: '',
            date1: '',
            date2: '',
            StagingVisible: false,
            StagingForm: [],
            total: 0,
            pagesize: 10,
            pagenum: 1,
            tableData: [],
            leaveVisible: false,
            ruleForm: {},
            categoryOptions: [],
            query: {
                id: '',
                nickName: ''
            },
            rules: {
                content: [
                    { required: true, message: '请输入申请原因', trigger: 'blur' },
                ],
                leaveTime: [
                    { required: true, message: '请选择离校时间', trigger: 'blur' },
                ],
                backTime: [
                    { required: true, message: '请选择回校时间', trigger: 'blur' },
                ],
                approvalPersonId: [
                    { required: true, message: '请选择审批教师', trigger: 'blur' },
                ],
                annex: [{ required: true, message: '请上传离校证明', trigger: 'blur' },]
            }
        };
    },
    methods: {

        //获取教师用户列表
        getTeacherUserList() {
            GetUserInfoListByParamsAPI({
                roleName: 'ROLE_TEACHER'
            }).then(res => {
                this.categoryOptions = res.data.data
                console.log("categoryOptions", this.categoryOptions)
            })
        },

        //教师用户列表是通过接口请求列表
        handleChangeTeacher(id) {
            let obj = {};
            obj = this.categoryOptions.find((item) => {
                return item.id === id; //筛选出匹配数据
            });
            this.ruleForm.approvalPersonId = obj.id;
            this.ruleForm.approvalPerson = obj.nickName;
        },

        handleChangeTeacherStaging(id) {
            let obj = {};
            obj = this.categoryOptions.find((item) => {
                return item.id === id; //筛选出匹配数据
            });
            this.StagingForm.approvalPersonId = obj.id;
            this.StagingForm.approvalPerson = obj.nickName;
        },


        //搜索
        selectByStatus() {
            GetApplicationInfoListAPI({
                applyPersonId: sessionStorage.getItem('userId'),
                status: this.status
            }).then(res => {
                this.tableData = res.data.data
                this.total = this.tableData.length
                console.log(res)
            })
        },
        // 删除已保存
        deleteStaging() {
            RemoveApplicationInfoAPI({
                id: this.StagingForm.id
            }).then(res => {
                if (res.data.code == 200) {
                    this.$message.success("删除成功")
                    this.StagingVisible = false
                }
                else {
                    this.$message.error("删除失败")
                }
                this.getApplication()
            })
        },
        //编辑
        edit(info) {
            this.StagingVisible = true
            this.StagingForm = info
            this.tableData1 = info.annex
        },
        // 请假申请的文件上传前
        beforeUpload(file) {
            if (file) {
                formData.append('afiles', file)
            }
            else {
                console.log("6")
            }
        },
        // 请假申请的文件上传
        upload() {
            postImage(formData).then(res => {
                res.data.data.forEach(element => {
                    this.ruleForm.annexId = element.id
                });
                if (this.staginging == true) {
                    this.ruleForm.status = 1
                    AddApplicationInfoAPI(this.ruleForm).then(res => {
                        if (res.data.code = 200) {
                            this.$message.success("暂存成功")
                            this.leaveVisible = false
                            this.getApplication()
                            this.staginging = false
                        }
                        else {
                            this.$message.error("暂存失败")
                        }
                    })
                }
                else if (this.adding == true) {
                    this.ruleForm.status = 2
                    AddApplicationInfoAPI(this.ruleForm).then(res => {
                        if (res.data.code = 200) {
                            this.$message.success("申请成功")
                            this.leaveVisible = false
                            this.getApplication()
                            this.adding = false
                        }
                        else {
                            this.$message.error("申请失败")
                        }
                    })
                }
            })
        },

        // 获取请假信息
        getApplication() {
            GetApplicationInfoListAPI({
                applyPersonId: sessionStorage.getItem('userId')
            }).then(res => {
                this.tableData = res.data.data
                this.total = this.tableData.length
                console.log(res)
            })
        },
        // 提交暂存
        staging() {
            if (this.fileUpload == true) {
                this.staginging = true
                this.$refs.uploadBox.submit()
                this.fileUpload = false
            }
            else if (this.fileUpload == false) {
                this.ruleForm.status = 1
                AddApplicationInfoAPI(this.ruleForm).then(res => {
                    if (res.data.code = 200) {
                        this.$message.success("暂存成功")
                        this.leaveVisible = false
                        this.getApplication()
                        this.staginging = false
                    }
                    else {
                        this.$message.error("暂存失败")
                    }
                })
            }

        },
        // 提交申请
        async submitForm() {
            this.adding = true
            await this.$refs.uploadBox.submit()
        },

        //编辑文件上传前
        beforeUpdateUpload(file) {
            if (file) {
                formData1.append('afiles', file)
            }
            else {
                console.log("6")
            }
        },

        // 编辑的文件上传
        updateUpload() {
            postImage(formData1).then(res => {
                res.data.data.forEach(element => {
                    this.middleList.annexId = element.id
                });
                if (this.UpdateStaging == true) {
                    this.middleList.status = 1
                    UpdateApplicationInfoAPI(this.middleList).then(res => {
                        if (res.data.code = 200) {
                            this.StagingVisible = false;
                            this.$message.success("暂存成功")
                            this.getApplication()
                            this.UpdateStaging = false
                            this.StagingVisible = false
                        }
                        else {
                            this.$message.error("暂存失败")
                        }
                    })
                }
                else if (this.UpdateAdding == true) {
                    this.middleList.status = 2
                    UpdateApplicationInfoAPI(this.middleList).then(res => {
                        if (res.data.code == 200) {
                            this.$message.success("操作成功")
                            this.getApplication()
                            this.UpdateAdding = false
                            this.StagingVisible = false
                        }
                        else {
                            this.$message.success("操作失败")
                        }
                    })
                }
            })
        },
        // 修改暂存信息
        async updateStaging(info) {
            this.middleList = JSON.parse(JSON.stringify(info))
            if (this.fileUpload1 == true) {
                this.UpdateStaging = true
                await this.$refs.updateBox.submit()
                this.fileUpload1 = false
            }
            else if (this.fileUpload == false) {
                this.middleList.status = 1
                UpdateApplicationInfoAPI(this.middleList).then(res => {
                    if (res.data.code = 200) {
                        this.StagingVisible = false
                        this.$message.success("暂存成功")
                        this.getApplication()
                        this.UpdateStaging = false
                    }
                    else {
                        this.$message.error("暂存失败")
                    }
                })
            }
        },

        // 上传暂存信息
        async updateSubmit(info) {
            this.middleList = JSON.parse(JSON.stringify(info))
            this.UpdateAdding = true
            await this.$refs.updateBox.submit()
        },
        //  关闭预览图片
        closeImgViewer() {
            this.imgViewerVisible = false;
            this.urlList = []
        },
        // 上传暂存信息
        async updateSubmit(info) {
            this.middleList = JSON.parse(JSON.stringify(info))
            if (this.fileUpload1 == true) {
                this.UpdateAdding = true
                await this.$refs.updateBox.submit()
            }
            else if (this.fileUpload == false) {
                this.middleList.status = 2
                UpdateApplicationInfoAPI(this.middleList).then(res => {
                    if (res.data.code == 200) {
                        this.StagingVisible = false;
                        this.$message.success("操作成功")
                        this.getApplication()
                        this.UpdateAdding = false
                    }
                    else {
                        this.$message.success("操作失败")
                    }
                })
            }

        },
        //  关闭预览图片
        closeImgViewer() {
            this.imgViewerVisible = false;
            this.urlList = []
        },

        // 预览文件图片
        viewRow(info) {
            this.imgViewerVisible = true
            GetBinDingAPI(info.id).then(res => {
                this.urlList.push(res.data.data)
            })
        },
        // 移除文件列表中的文件
        deleteRow(info) {
            RemoveInfo({ id: info.refId }).then(res => {
                if (res.data.code == 200) {
                    this.$message.success("删除成功")
                    this.key = 3
                    // this.StagingVisible = false
                }
                // this.tableData1 = info
            })

        },
        // 重置申请表单
        resetForm() {
            this.$refs.ruleFormRef.resetFields();
            this.leaveVisible = false
        },
        //监听pagesize改变的事件
        handleSizeChange(newSize) {
            this.pagesize = newSize
        },
        // 预览文件图片
        viewRow(info) {
            this.imgViewerVisible = true
            GetBinDingAPI(info.id).then(res => {
                this.urlList.push(res.data.data)
            })
        },
        // 移除文件列表中的文件
        deleteRow(info) {
            RemoveInfo({ id: info.refId }).then(res => {
                if (res.data.code == 200) {
                    this.$message.success("删除成功")
                    this.key = 3
                    // this.StagingVisible = false
                }
                // this.tableData1 = info
            })

        },
        // 重置申请表单
        resetForm() {
            this.$refs.ruleFormRef.resetFields();
            this.leaveVisible = false
        },
        //监听pagesize改变的事件
        handleSizeChange(newSize) {
            this.pagesize = newSize
        },

        //监听页码值改变的事件
        handleCurrentChange(newPage) {
            this.pagenum = newPage
        },

    },
    filters: {
        ellipsis(value) {
            if (!value) return ''
            if (value.length > 100) {
                return value.slice(0, 190) + '...'
            }
            return value
        }
    },
    created() {
        this.getApplication()
        this.getTeacherUserList()
    }
}
</script>

<style>
.demo-table-expand {
    font-size: 0;
}

.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}

.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}
</style>